package longrise.phone.com.bjjt_henan.main;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.FormParameter;
import com.longrise.android.ILFMsgListener;
import com.longrise.android.ILSMsgListener;
import com.longrise.android.LFView;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.PrefUtils;
import com.longrise.bjjt.util.UiUtil;

import longrise.phone.com.bjjt_henan.MainActivity;
import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.DialogUtils;
import longrise.phone.com.bjjt_henan.bindinginformation.PersonalInfoView;

/**
 * 主页面
 */
public class NewMainView extends LFView implements RadioGroup.OnCheckedChangeListener, ILSMsgListener,
        ILFMsgListener {

    private View mView;

    private Context mContext;

    private LinearLayout bodyLayout;

    private RadioGroup radioGroup;

    private NewHomeView homeView;//首页

    private NewKckpView kckpView;//快处快赔

    private PersonalInfoView myView;//我的

    private EntityBean bindBean;//是否绑定的返回参数

    protected boolean isExit = false;

    private int bindState = -1;//-1表示查询失败;0表示查询成功;1表示数据完整

    private String redes;//失败的提示

    private LFView curShowView;//当前显示的页面

    public NewMainView(Context context) {
        super(context);
        this.mContext = context;
    }

    @Override
    public View getView() {
        return mView;
    }

    @Override
    public FormParameter getFormParameter() {
        FormParameter fp = new FormParameter();
        fp.setShowtitle(false);
        return fp;
    }

    @Override
    public void init() {
        if (mContext == null) {
            return;
        }
        mView = LayoutInflater.from(mContext).inflate(R.layout.view_newmain, null);
        if (mView == null) {
            return;
        }
        bodyLayout = (LinearLayout) mView.findViewById(R.id.newmain_layout);
        radioGroup = (RadioGroup) mView.findViewById(R.id.newmain_rgroup);
        setListen(true);
        switchView(0);

        getBindData(true);
    }

    //切换显示的页面
    private void switchView(int pos) {
        if (bodyLayout == null) {
            return;
        }
        if (pos == 0) {//首页
            if (homeView == null) {
                homeView = new NewHomeView(mContext);
                homeView.init();
                homeView.refresh();
            }
            curShowView = homeView;
        } else if (pos == 1) {//快处快赔
            if (kckpView == null) {
                kckpView = new NewKckpView(mContext);
                kckpView.init();
                kckpView.refresh();
            }
            curShowView = kckpView;
        } else if (pos == 2) {
            if (myView == null) {
                myView = new PersonalInfoView(mContext, null);
                myView.init();
                myView.refresh();
            }
            curShowView = myView;
        }
        //添加到主页面中
        bodyLayout.removeAllViews();
        bodyLayout.addView(curShowView.getView(), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        //刷新数据
        refreshView();
    }

    private void setListen(boolean flag) {
        if (radioGroup != null) {
            radioGroup.setOnCheckedChangeListener(flag ? this : null);
        }
        if (flag) {
            addILSMsgListener(this);
            addILFMsgListener(this);
        } else {
            removeILSMsgListener(this);
            removeILFMsgListener(this);
        }
    }

    @Override
    public void refreshByTime() {

    }

    @Override
    public void refresh() {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.newmain_rbtn_home://首页
                switchView(0);
                break;
            case R.id.newmain_rbtn_kckp://快处快赔
                switchView(1);
                break;
            case R.id.newmain_rbtn_my://我的
                switchView(2);
                break;
            default:
                break;
        }
    }

    /**
     * 刷新当前显示界面的数据
     */
    private void refreshView() {
        if (curShowView instanceof NewHomeView) {

        } else if (curShowView instanceof NewKckpView) {
            ((NewKckpView) curShowView).setBindBean(bindBean);
            ((NewKckpView) curShowView).setBindState(bindState);
            ((NewKckpView) curShowView).setRedes(redes);
        } else if (curShowView instanceof PersonalInfoView) {
            ((PersonalInfoView) curShowView).setBindBean(bindBean);
        }
    }

    /**
     * 查询绑定的车辆信息
     */
    private void getBindData(final boolean isToast) {
        try {
            BaseApplication application = (BaseApplication) mContext
                    .getApplicationContext();
            final EntityBean baseBean = application.getLoginInfo().getBean("userinfo");
            String userId = baseBean.getString("id");
            String userflag = application.getKckpName();
            String token = application.getToken();
            DialogUtils.showDialog(mContext);
            ApiImpI.getInstance(application).bindState(userId, userflag, token,
                    new ApiImpI.RequestCallBack() {
                        @Override
                        public void onError(String error) {
                            DialogUtils.closeDialog();
                            if (!TextUtils.isEmpty(error)) {
                                UiUtil.showToast(mContext, error);
                            }
                        }

                        @Override
                        public void onSuccess(Object result) {
                            DialogUtils.closeDialog();
                            EntityBean bean = (EntityBean) result;
                            if (bean != null) {
                                bindState = 0;
                                bindBean = bean.getBean("data");
                                String restate = bean.getString("restate");
                                redes = bean.getString("redes");
                                if ("1".equals(restate)) {//用户已绑定驾驶证和行驶证信息
                                    bindState = 1;
                                } else if (isToast) {
                                    if (!TextUtils.isEmpty(redes)) {
                                        UiUtil.showToast(mContext, redes);
                                    }
                                }
                                refreshView();
                                //保存车辆和驾驶证的数据
                                String carInfo = com.longrise.LEAP.Base.IO.JSONSerializer.getInstance().Serialize(bean);
                                PrefUtils.setString(mContext, "carinfo", carInfo);
                                LSMsgCall(102, "carinfo");
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object onLSMsg(int arg0, Object... arg1) {
        if (arg0 == 99) {//重新获取绑定的数据
            getBindData(false);
        }
        return null;
    }

    @Override
    public Object onLFMsg(int i, Object... objects) {
        if (i == -10) {
            exit();
            return false;
        }
        return null;
    }

    private void exit() {
        if (!this.isExit) {
            this.isExit = true;
            Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            this.mHandler.sendEmptyMessageDelayed(0, 2000L);
        } else {
            ((MainActivity) mContext).finish();
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public void OnDestroy() {
        super.OnDestroy();
        setListen(false);
        removeILFMsgListener(this);
        removeILSMsgListener(this);
        if (null != homeView) {
            homeView.OnDestroy();
            homeView = null;
        }
        if (null != kckpView) {
            kckpView.OnDestroy();
            kckpView = null;
        }
        if (null != myView) {
            myView.OnDestroy();
            myView = null;
        }
        if (null != bodyLayout) {
            bodyLayout.removeAllViews();
            bodyLayout = null;
        }
        radioGroup = null;
        mView = null;
        mHandler = null;
        curShowView = null;
    }
}
